<?php

function format_time() {
    return date('Y-m-d H:i:s');
}

/**
 * 
 * @param array $items
 * @param int $id
 * @param ind $pid
 * @param string $son
 * @return array
 */
function getDataTree($items, $id = 'id', $pid = 'pid', $son = '_child') {
    $tree = array(); //格式化的树
    $tmpMap = array();  //临时扁平数据

    foreach ($items as $item) {
        $tmpMap[$item[$id]] = $item;
    }

    foreach ($items as $item) {
        if (isset($tmpMap[$item[$pid]])) {
            $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
        } else {
            $tree[] = &$tmpMap[$item[$id]];
        }
    }
    return $tree;
}

//curl接口调用，post传值
function post_curl($url, $post_data) {
    $ch = curl_init();
    // print_r($ch);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}

function arr_sort($array, $key, $order = "asc") {//asc是升序 desc是降序
    $arr_nums = $arr = array();

    foreach ($array as $k => $v) {

        $arr_nums[$k] = $v[$key];
    }

    if ($order == 'asc') {

        asort($arr_nums);
    } else {

        arsort($arr_nums);
    }

    foreach ($arr_nums as $k => $v) {

        $arr[$k] = $array[$k];
    }

    return $arr;
}

/**
 * 导出excel.xls文件
 * @param string $fileName 文件名
 * @param array $arrHead   表头
 * @param array $data      表值
 */
function exportExcel($fileName, $arrHead, $data) {

    import("Org.Util.PHPExcel");
    import("Org.Util.PHPExcel.Writer.Excel5");
    import("Org.Util.PHPExcel.IOFactory.php");
    //对数据进行检验
    if (empty($data) || !is_array($data)) {
        die("导出excel数据不存在");
    }
    //检查文件名
    if (empty($fileName)) {
        exit;
    }

    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";

    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();

    //设置表头
    $key = ord("A");
    foreach ($arrHead as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }

    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { //行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    // $objPHPExcel->getActiveSheet()->setTitle('test');
    //打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

/**
 * 导入excel文件
 * @param string $filename
 */
function importExcel($filename) {
    $arr = array();
    $ext = substr($filename, strrpos($filename, '.') + 1);

    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
    import("Org.Util.PHPExcel");

    //创建PHPExcel对象，注意，不能少了\
    $PHPExcel = new \PHPExcel();
    //如果excel文件后缀名为.xls，导入这个类
    if ($ext == 'xls') {
        import("Org.Util.PHPExcel.Reader.Excel5");
        $PHPReader = new \PHPExcel_Reader_Excel5();
    } else {
        //如果excel文件后缀名为.xlsx，导入这下类
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader = new \PHPExcel_Reader_Excel2007();
    }

    //载入文件
    $PHPExcel = $PHPReader->load($filename);
    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $currentSheet = $PHPExcel->getSheet(0);
    //获取总列数
    $allColumn = $currentSheet->getHighestColumn();
    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
    for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
        //从哪列开始，A表示第一列
        for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
            //数据坐标
            $address = $currentColumn . $currentRow;
            //读取到的数据，保存到数组$arr中
            $arr[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
            $cell = $currentSheet->getCell($address);

            // http://www.osakac.ac.jp/labs/koeda/tmp/phpexcel/Documentation/API/PHPExcel_Shared/PHPExcel_Shared_Date.html
            if (PHPExcel_Shared_Date::isDateTime($cell)) {
                $arr[$currentRow][$currentColumn] = gmdate("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
                // $arr[$currentRow][$currentColumn]=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
            } else {
                $arr[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
            }
        }
    }
    return $arr;
}

/**
 * 导入excel文件
 * @param string $filename
 */
function autoimportExcel($filename, $ext) {
    $arr = array();


    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
    import("Org.Util.PHPExcel");

    //创建PHPExcel对象，注意，不能少了\
    $PHPExcel = new \PHPExcel();
    //如果excel文件后缀名为.xls，导入这个类
    if ($ext == 'xls') {
        import("Org.Util.PHPExcel.Reader.Excel5");
        $PHPReader = new \PHPExcel_Reader_Excel5();
    } else {
        //如果excel文件后缀名为.xlsx，导入这下类
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader = new \PHPExcel_Reader_Excel2007();
    }

    //载入文件
    $PHPExcel = $PHPReader->load($filename);
    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $currentSheet = $PHPExcel->getSheet(0);
    //获取总列数
    $allColumn = $currentSheet->getHighestColumn();
    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
    for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
        //从哪列开始，A表示第一列
        for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
            //数据坐标
            $address = $currentColumn . $currentRow;
            //读取到的数据，保存到数组$arr中
            $arr[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
            $cell = $currentSheet->getCell($address);

            // http://www.osakac.ac.jp/labs/koeda/tmp/phpexcel/Documentation/API/PHPExcel_Shared/PHPExcel_Shared_Date.html
            if (PHPExcel_Shared_Date::isDateTime($cell)) {
                $arr[$currentRow][$currentColumn] = gmdate("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
                // $arr[$currentRow][$currentColumn]=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
            } else {
                $arr[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
            }
        }
    }
    return $arr;
}

//检查是否账号
function check_ismobile($mobile) {
    if (preg_match('/^1([358]\d{9}|7[013678]\d{8}|4[25789]\d{8})$/', $mobile)) {
        return true;
    } else {
        return false;
    }
}

//检查是否为座机电话号码
function check_istel($tel) {
    if (preg_match('/^([0-9]{3,4}[-]?)?[0-9]{7,8}$/', $tel)) {
        return true;
    } else {
        return false;
    }
}

//检查是否为账号或座机电话
function check_isphone($phone) {
    if (check_ismobile($phone) || check_istel($phone)) {
        return true;
    } else {
        return false;
    }
}

function check_url($url) {
    if (!preg_match('/^(http|https):\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is', $url)) {
        return false;
    }
    return true;
}

//获取请求参数列表字段，(只支持整型数据)
function get_id_list($key) {
    return I($key, '', '/^([0-9]{1,}[,]?)+$/');
}

/**
 * 生成验证码
 * @param string $strKey 缓存KEY
 * @return string
 */
function createVerify($strKey) {
    $strRand = mt_rand(100000, 999999);
    S($strKey, $strRand, 1800);
    return $strRand;
}

/**
 * 发送短信
 * @param string $strPhone 账号
 * @param string $strContent 内容
 * @return void
 */
function sys_sms($strPhone, $strContent) {

    import("SMS.send");
    return sendsms($strPhone, $strContent);
}

/**
 * 是否账号码
 * @param string $phone 账号
 * @return bool
 */
function isPhone($phone) {
    $chars = "/^0{0,1}(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/";
    if (preg_match($chars, $phone)) {
        return true;
    } else {
        return false;
    }
}

function sign_request($url, $data, $type = 'GET', $optional_headers = null) {
    ksort($data);
    $postStr = http_build_query($data);
    $sign = md5($postStr . C('API_ENCRYPT_KEY'));
    $data['sign'] = $sign;

    $params = array('http' => array(
            'method' => $type
    ));
    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($url . '&' . $data, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with $url");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from $url");
    }
    return $response;
}

function do_get_request($url, $data, $timeout = 3) {
    $opts = array(
        'http' => array(
            'method' => "GET",
            'timeout' => $timeout,
        )
    );
    $ctx = stream_context_create($opts);
    $url = $url . '&' . http_build_query($data);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with $url");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from $url");
    }
    return $response;
}

/**
 * 是否Email
 * @param string $email 邮箱
 * @return bool
 */
function isEmail($email) {
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
    if (strpos($email, '@') !== false && strpos($email, '.') !== false) {
        if (preg_match($chars, $email)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * 格式化整数分数带小数0的情况（将80.0转换成80）
 * @param float $score 传入的分数值
 * @return int/float Description
 */
function format_score($score) {
    $arrStr = explode('.', $score);
    if ($arrStr[1] === '0') {
        $score = intval($score);
    }
    return $score;
}

/**
 * 阿拉伯数字转中文数字
 * @param int $num 阿拉伯数字
 */
function ToChinaseNum($num) {
    $char = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
    $dw = array("", "十", "百", "千", "万", "亿", "兆");
    $retval = "";
    $proZero = false;
    for ($i = 0; $i < strlen($num); $i++) {
        if ($i > 0)
            $temp = (int) (($num % pow(10, $i + 1)) / pow(10, $i));
        else
            $temp = (int) ($num % pow(10, 1));

        if ($proZero == true && $temp == 0)
            continue;

        if ($temp == 0)
            $proZero = true;
        else
            $proZero = false;

        if ($proZero) {
            if ($retval == "")
                continue;
            $retval = $char[$temp] . $retval;
        } else
            $retval = $char[$temp] . $dw[$i] . $retval;
    }
    if ($retval == "一十")
        $retval = "十";
    return $retval;
}

/**
 * @desc 封装 curl 的调用接口，post的请求方式
 */
function doCurlPostRequesta($url, $arrDataTest, $timeout = 5) {
    if ($url == '' || $arrDataTest == '' || $timeout <= 0) {
        return false;
    }
    ksort($arrDataTest);
    $strPostDataTest = http_build_query($arrDataTest);
    $strSignTest = md5($strPostDataTest . 'txws_test');
    $_GET = $arrDataTest;
    $_GET['sign'] = $strSignTest;

    $con = curl_init((string) $url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int) $timeout);
    return curl_exec($con);
}

/**
 * 企业能力测评级别
 */
function abilityLevelName($iLevel) {
    $arrLevel = array(
        0 => '新手',
        1 => '初级',
        2 => '中级',
        3 => '高级'
    );

    if (!is_numeric($iLevel)) {
        return $arrLevel;
    } else {
        return $arrLevel[$iLevel];
    }
}

/**
 * token加密：为终端提供唯一标识
 * @param type $iUserId
 * @return string
 */
function token_encrypt($iUserId) {
    import('Think.Crypt');
    $value = $iUserId . '-' . microtime();
    $token = \Think\Crypt::encrypt($value, C('COOKIE_ENCRYPT_KEY'));
    return $token;
}

/**
 * token解密
 * @param type $userId
 * @return array [user_id,time]
 */
function token_decrypt($token) {
    import('Think.Crypt');
    $value = \Think\Crypt::decrypt($token, C('COOKIE_ENCRYPT_KEY'));
    return explode('-', $value);
}

/**
 * redis设置缓存
 * @param type $sessData
 * @return boolean
 */
function session_redis_set($sessData) {
    import('Think.Cache.Driver.Redis');
    return \Think\Cache\Driver\Redis::getInstance()->set(C('REDIS_SESSION_PREFIX') . $sessData['iUserId'], json_encode($sessData));

}

/**
 * redis获取
 * @param type $userId
 * @return boolean
 */
function session_redis_get($userId) {
    import('Think.Cache.Driver.Redis');
    $userInfo = \Think\Cache\Driver\Redis::getInstance()->get(C('REDIS_SESSION_PREFIX') . $userId);
    if ($userInfo) {
        //延长有效期
        \Think\Cache\Driver\Redis::getInstance()->expire(C('REDIS_SESSION_PREFIX') . $userId);
        return $userInfo;
    } else {
        return false;
    }
}

/**
 * redis删除
 * @param type $userId
 * @return type
 */
function session_redis_rm($userId) {
    import('Think.Cache.Driver.Redis');
    return \Think\Cache\Driver\Redis::getInstance()->rm(C('REDIS_SESSION_PREFIX') . $userId);
}

/**
 * 获取用户基本信息并延长登录时间
 * @param type $userId
 * @return boolean
 */
function get_redis_userinfo($userId) {
    import('Think.Cache.Driver.Redis');
    $userInfo = \Think\Cache\Driver\Redis::getInstance()->get(C('REDIS_SESSION_PREFIX') . $userId);
    if ($userInfo) {
        //延长有效期
        \Think\Cache\Driver\Redis::getInstance()->expire(C('REDIS_SESSION_PREFIX') . $userId);
        return $userInfo;
    } else {
        return false;
    }
}

/**
 * 设置redis中用户基本信息
 * @param type $userId  
 * @param type $key   需要设置的数组key
 * @param type $value 设置的值
 */
function set_redis_userinfo($userId, $key,$value){
    import('Think.Cache.Driver.Redis');
    $userInfo = \Think\Cache\Driver\Redis::getInstance()->get(C('REDIS_SESSION_PREFIX') . $userId);
    $userInfo[$key] = $value;
    return \Think\Cache\Driver\Redis::getInstance()->set(C('REDIS_SESSION_PREFIX') . $userId, json_encode($userInfo));
}